<?php
namespace libraries;

/**
 * 
 * @author fzq
 * @date 2016-09-27
 */
class IpLocation implements \Phalcon\Di\InjectionAwareInterface
{
	private $_di;
	
	const RETTYPE_JSON = 'json';
	const RETTYPE_XML = 'xml';
	
	public function getIpLocation( $strIp, $strRetType = self::RETTYPE_JSON )
	{
		$ipCfg = $this->_di->get( 'ipCfg' );
		
		//************1.根据IP/域名查询地址************
		$params = array(
				"ip" => $strIp,//需要查询的IP地址或域名
				"key" => $ipCfg->appkey,//应用APPKEY(应用详细页查询)
				"dtype" => $strRetType,//返回数据的格式,xml或json，默认json
		);
		
		$strParams = http_build_query( $params );
		$content = $this->juhecurl( $ipCfg->url, $strParams );
		
		if( self::RETTYPE_JSON == $strRetType )
		{
			return json_decode( $content, true );
		}
		else
		{
			return $content;
		}
	
	}
	
	
	/**
	 * 请求接口返回内容
	 * @param  string $url [请求的URL地址]
	 * @param  string $params [请求的参数]
	 * @param  int $ipost [是否采用POST形式]
	 * @return  string
	 */
	private function juhecurl( $url, $params = false, $ispost = 0 )
	{
		$httpInfo = array();
		$ch = curl_init();
	
		curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
		curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
		curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
		curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		
		if( $ispost )
		{
			curl_setopt( $ch , CURLOPT_POST , true );
			curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
			curl_setopt( $ch , CURLOPT_URL , $url );
		}
		else
		{
			if($params)
			{
				curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
			}
			else
			{
				curl_setopt( $ch , CURLOPT_URL , $url);
			}
		}
		
		$response = curl_exec( $ch );
		
		if ($response === FALSE) 
		{
			//echo "cURL Error: " . curl_error($ch);
			return false;
		}
		$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
		$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
		curl_close( $ch );
		return $response;
	}
	
	/* 
	 * @see \Phalcon\Di\InjectionAwareInterface::setDI()
	 */
	public function setDI(\Phalcon\DiInterface $dependencyInjector) 
	{
		$this->_di = $dependencyInjector;
	}

	/* 
	 * @see \Phalcon\Di\InjectionAwareInterface::getDI()
	 */
	public function getDI() 
	{
		return $this->_di;
	}

}